package leetcode.D100.T64;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: DYZ
 * @Create: 2021-08-12 23:25:51 星期四
 */

public class Solution {
    /**
     * 一刷
     * 和62差不多，都是动态规划，但是可以直接修改grid，不用另外创建dp数组，因此空间复杂度为O(1)
     * @param grid
     * @return
     */
    /*public int minPathSum(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        for(int i=1; i<n; ++i) {
            grid[0][i] = grid[0][i-1] + grid[0][i];
        }
        for(int i=1; i<m; ++i) {
            grid[i][0] = grid[i-1][0] + grid[i][0];
            for(int j=1; j<n; ++j) {
                grid[i][j] = Math.min(grid[i][j-1], grid[i-1][j]) + grid[i][j];
            }
        }
        return grid[m-1][n-1];
    }*/

    // 二刷
    /*public int minPathSum(int[][] grid) {
        for(int i=0; i<grid.length; ++i) {
            if (i > 0)
                grid[i][0] += grid[i-1][0];
            for(int j=1; j<grid[0].length; ++j) {
                if(i == 0)
                    grid[i][j] += grid[i][j-1];
                else
                    grid[i][j] += Math.min(grid[i][j-1], grid[i-1][j]);
            }
        }
        return grid[grid.length-1][grid[0].length-1];
    }*/

    // 三刷
    public int minPathSum(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        for (int j = 1; j < n; j++) {
            grid[0][j] += grid[0][j-1];
        }
        for (int i=1; i<m; ++i) {
            grid[i][0] += grid[i-1][0];
            for (int j=1; j<n; ++j) {
                grid[i][j] += Math.min(grid[i-1][j], grid[i][j-1]);
            }
        }
        return grid[m-1][n-1];
    }
}
